import axios, { AxiosProgressEvent } from 'axios';
import { blobValidate, clearEmptyKey } from './utils/utils';
import main from './main';
import { saveAs } from 'file-saver';
import { Message } from '@arco-design/web-react';
import { CardDetailConvert } from './pages/components/cardCreate/types';
import { CardDetailConvertOrder } from './types';
const api = main.api

api.interceptors.request.use(config => {
  const token = main?.token || '';
  // if (!token) {
  //   return Promise.reject(Message.error('token is null'));
  // }
  if (token) {
    config.headers['Authorization'] = `Bearer ${token}`;
  }
  return config;
});
export async function apiGetCardDetails(data: any) {
  let res = await api.get(`/product/prdCard/getCardInfo4CustomerServer`,{params:data});
  return res;
}
export async function apiGetCardIccidList(data: any) {
  let res = await api.get(`/product/prdCard/getCardList4CustomerServer`,{params:data});
  return res;
}
// 获取流量卡资费列表
export async function getFlowConfigList(params:any) {
  return await main.api.get(`/system/prdCardConver/getFlowConfigList`, { params: params });
  
}
// 查询资费信息
export async function getEmConfigList(params?:any) {
  return await main.api.get(`/system/prdCardConver/getEmConfigList`, { params: params });
}

// 查询资费信息
export async function getProductList(params:any) {
  return await main.api.get(`/system/prdCardConver/getProductList`, { params: params });
}

/** 根据转卡类型查询产品列表 */
export async function apiGetProductByConvertOrderType(type: string, iccid?: string) {
  return await main.api.get(`/card/cardDetailConvertOrder/getProductList`, { params: { type, iccid } });
}
// 更新
export async function apiUpdateCardDetailConvertOrderDetail(
  cardDetailConvertOrderId: string,
  data: any
) {
  let fn = cardDetailConvertOrderId === 'create' ? main.api.post : main.api.put;
  let res = await fn(`/system/prdCardConver`, data);

  return res;
}
/** 获取设备配置的产品列表 */
export async function apiGetEmConfigProductList() {
  return await main.api.get(`/card/cardDetailConvertOrder/getEmConfigList`);
}
/** 根据卡号查询待支付转卡记录 */
export async function apiGetCardDetailConvertOrderDetailByIccid(params: any) {
  return await main.api.get(`/system/prdCardConver/getbyIccId`, { params });
}
// 字典数据列表
export async function apiGetDictDataList(type: string) {
  let res = await api.get(`system/dict/data/type/${type}`);
  return res;
}
export async function apiCardDetailList(params: any) {
  let res = await api.get(`/card/cardDetail/list`,{params});
  return res;
}

// 列表
export async function apiGetPayCouponCardUserList(pageNum: number, pageSize: number, params?: any) {
  let tParams = params ? clearEmptyKey(params) : null;
  let res = await api.get('/card/payCouponCardUser/list', { params: { pageNum, pageSize, ...tParams } });

  return res;
}

export async function apiGetPayCouponList(pageNum: number, pageSize: number, params?: any) {
  let tParams = params ? clearEmptyKey(params) : null;
  let res = await api.get('/product/prdCardCoupon/list', { params: { pageNum, pageSize, ...tParams } });

  return res;
}

// 赠送优惠券
export async function apiPayCouponCardUser(data: any) {
  let res = await api.post(`/product/prdCardCouponRecord`, data);
  return res;
}
export async function apiGetTaskMqCardDetailList(pageNum: number, pageSize: number, params?: any) {
  let tParams = params ? clearEmptyKey(params) : null;
  let res = await api.get('/card/taskMqCardDetail/list', { params: { pageNum, pageSize, ...tParams } });

  return res;
}
// 详情
export async function apiGetTaskMqCardDetail(taskMqCardId: string) {
  let res = await api.get(`/card/taskMqCard/${taskMqCardId}`);

  return res;
}
// 上传文件
export async function apiUploadFile(file: File, uploadProgress?: (loaded: number, total: number) => void) {
  main.uploadProgress = uploadProgress;
  let res = await api.post(
    `/resource/oss/upload`,
    { file },
    {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    }
  );

  return res;
}
// 充销记录
export async function apiGetCardDetail(iccid: string,pageNum:string | number,pageSize:string | number) {
  let res = await api.get(`/product/prdBalanceChangesCard/list?pageNum=${pageNum}&pageSize=${pageSize}&iccid=${iccid}`);

  return res;
}
// 充值记录
export async function apiGetOrderByColumn(iccid: string,pageNum:string | number,pageSize:string | number) {
  let res = await api.get(`card/cardDetailWalletOrder/list?pageNum=${pageNum}&pageSize=${pageSize}&iccid=${iccid}&orderByColumn=createTime&isAsc=desc`);

  return res;
}
// 消费记录
export async function apiGeCardDetailWalletLog(iccid: string,pageNum:string | number,pageSize:string | number) {
  let res = await api.get(`card/cardDetailWalletLog/list?pageNum=${pageNum}&pageSize=${pageSize}&iccid=${iccid}&orderByColumn=createTime&isAsc=desc`);

  return res;
}
// 订购信息
export async function apiGeCardPackOrder(iccid: string,pageNum:string | number,pageSize:string | number) {
  let res = await api.get(`/product/prdPackageOrder/list?pageNum=${pageNum}&pageSize=${1000}&iccid=${iccid}`);

  return res;
}
// 获取详细信息
export async function apiGetOtherDetail(id: number) {
  return main.api.get(`/card/cardDetail/getOtherDetail/${id}`);
}
// 获取详细信息-退款
export async function apiGetOtherChatDetail(id: number) {
  return main.api.get(`/chat/cardDetail/getOtherDetail/${id}`);
}
// 广电机卡分离开机
export async function apiCardDetailGdOpen(data: any) {
  return main.api.post('/card/cardDetail/gdOpen', data);
}
// 卡操作
export async function apiOperateCard(data: any) {
  let res = await api.get(`/product/prdCard/updateCardInfo`, {params:data});
  return res;
}
// 开关机
export async function apiSyncOperateStartAndStop(data: any) {
  let res = await api.get(`/product/prdCard/updateCardStatusNew`, { params: data });
  return res;
}
// 卡批量手动订购 模板下载
export async function apiImportFilesixteenTemplate() {
  await download('/card/cardImport/general/sixteen', {}, `批量手动订购模板_${new Date().getTime()}.xlsx`);
}
// 更新
export async function apiUpdateCardDetailDetail(cardDetailId: string, data: any) {
  let fn = cardDetailId === 'create' ? api.post : api.put;
  let res = await fn(`/card/cardDetail`, data);
  return res;
}
// 导入手动订购
export async function apiCardBuyOrder(exportName: string, url: string) {
  return api.get('/card/cardPackOrder/batchBuyPackOrder', { params: { exportName, url } });
}
// 列表
export async function apiGetTaskMqImportList(pageNum: number, pageSize: number, params?: any) {
  let tParams = params ? clearEmptyKey(params) : null;
  let res = await api.get('/card/taskMqImport/list', { params: { pageNum, pageSize, ...tParams } });

  return res;
}
// 导出
export async function apiExportTaskMqImportDetail(params: any) {
  return await api.get('/card/taskMqImportDetail/export', { params });
}
// 列表
export async function apiGetTaskMqImportDetailList(pageNum: number, pageSize: number, params?: any) {
  let tParams = params ? clearEmptyKey(params) : null;
  let res = await api.get('/card/taskMqImportDetail/list', { params: { pageNum, pageSize, ...tParams } });

  return res;
}
// 列表
export async function apiGetTaskMqExportList(pageNum: number, pageSize: number, params?: any) {
  let tParams = params ? clearEmptyKey(params) : null;
  let res = await api.get('/card/taskMqExport/list', { params: { pageNum, pageSize, ...tParams } });

  return res;
}
// 列表
export async function apiGetCardUserAddressList(pageNum: number, pageSize: number, params?: any) {
  let tParams = params ? clearEmptyKey(params) : null;
  let res = await api.get('/card/cardUserAddress/list', { params: { pageNum, pageSize, ...tParams } });

  return res;
}

// 更新
export async function apiUpdateCardDetailConvertDetail(cardDetailConvertId: number | string, data: CardDetailConvert) {
  let fn = cardDetailConvertId === 'create' ? api.post : api.put;
  let res = await fn('/card/cardDetailConvert', data);
  return res;
}
// iccid 卡号列表
export async function apiGetCardDetailList() {
  let res = await api.get('/card/cardDetail/list?pageNum=1&pageSize=1200', {});
  return res;
}

/**
 * 获取卡片套餐资费详情
 * @param cardId 卡ID
 * @returns
 */
export async function apiGetProductCore(cardId: string | number) {
  return api.get('/card/cardDetail/getProductCore', { params: { cardId } });
}

// 获取预设转卡链接
export async function apiGetPreSetConvertUrl(type: string, iccid?: string | number) {
  return api.get('/system/sysUserPreset/getDetailInfo', { params: { iccid, type } });
}

// 保存预设转卡链接
export async function apiSetPreSetConvertUrl(
  type: string,
  beforText?: string,
  afterText?: string,
  businessJson?: string[]
) {
  return api.post('/card/cardPresetRecommend/updateOrInsert', { type, beforText, afterText, businessJson });
}
// 设置标签
export async function apiCardSetTag(data: any) {
  let res = await api.get('/product/prdCard/stopServerTagName', { params:data });
  return res;
}
export async function download(url: string, params: any, filename: string) {
  try {
    let res = await api.post(url, params, {
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      responseType: 'blob',
    });
    let data = res.data;
    let isBlob = await blobValidate([data]);
    if (isBlob) {
      let blob = new Blob([data as unknown] as BlobPart[]);
      saveAs(blob, filename);
    } else {
      // @ts-ignore
      let resText = await data.text();
      let rspObj = JSON.parse(resText);
      Message.error(rspObj.msg || '系统未知错误，请反馈给管理员');
    }
  } catch (e) {
    Message.error('下载文件出现错误，请联系管理员！');
  }
}
// 加急
export async function apiCardDetailWalletRefundApplyEditTag(data: any) {
  let res = await api.post(`/product/prdPackageOrderRefund/pushback`, data);

  return res;
}
/**
 * 加急状态
 */
export async function apiGetUrgentInfo(id?: string | number) {
  var res = await api.get(`/card/cardDetailWalletRefundApply/urgentInfo`, { params: { id } });
  return res;
}
/**
 * 加急状态
 */
export async function apiGetProcessing4CustomerServer( iccid?: string | number) {
  var res = await api.get(`/product/prdCard/getProcessing4CustomerServer`, { params: {  iccid } });
  return res;
}
/**
 * 查询卡片冻结情况
 */
export async function apiGetCardFreezeStatus( id?: string | number) {
  var res = await api.get(`/system/prdCard/getCardFreezeStatus`, { params: {  id } });
  return res;
}
